﻿namespace BlazorAdmin.Tcp.Protocol
{
    /// <summary>
    /// 协议基类
    /// </summary>
    public abstract class ProtocolBase
    {
        /// <summary>
        /// 协议头
        /// </summary>
        public abstract byte[]? Header { get; protected set; }

        /// <summary>
        /// 表示一帧完整数据至少有多少固定长度
        /// </summary>
        public abstract int FixLength { get; protected set; }

        /// <summary>
        /// 数据长度
        /// </summary>
        public abstract int DataLen { get; protected set; }

        /// <summary>
        /// 检验和
        /// </summary>
        public abstract int CS { get; protected set; }

        /// <summary>
        /// 将数据帧解析成对应的协议对象
        /// </summary>
        /// <param name="frame">数据帧</param>
        /// <param name="start">起始位置</param>
        /// <param name="count">数据总数</param>
        /// <returns></returns>
        public abstract ProtocolBase? Analysis(byte[] frame, int start, int count);

        /// <summary>
        /// 构建数据帧
        /// </summary>
        /// <returns></returns>
        public abstract byte[]? Build();

        /// <summary>
        /// 判断数据帧是否为包头开始
        /// </summary>
        /// <param name="frame">数据帧</param>
        /// <param name="start">起始位置</param>
        /// <param name="count">数据总数</param>
        /// <returns></returns>
        protected bool StartWith(byte[] frame, int start, int count)
        {
            int hLen = null == Header ? 0 : Header.Length;
            if (count < hLen)
                return false;

            for (int i = 0; i < hLen; i++)
            {
                if (frame[start + i] != Header![i])
                    return false;
            }

            return true;
        }
    }
}